package cn.eonshine.base.core.util;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.google.common.collect.Maps;

import cn.hutool.core.util.ReflectUtil;

public class ClazzUtils {

	/**
	 * 
	 * @Title: convertBeanFeildToDBField   
	 * @Description: convert Bean key to db field key 
	 * by Alan 2019-03-26 09:44:14
	 * @param map
	 * @param clazz
	 * @return  Map
	 */
	public static Map<String, Object> convertBeanFieldToDBField(Map<String, Object> map, Class<?> clazz){
		Map<String, Object> convertMap = Maps.newHashMap();
		for (Entry<String, Object> ele : map.entrySet()) {
			if(ele.getValue() == null || StringUtils.isEmpty(ele.getValue().toString())) {
				continue;
			}
			String dbField =  ele.getKey();
			Field field = ReflectUtil.getField(clazz, dbField);
			TableField tf = field.getAnnotation(TableField.class);
			if(tf == null) {
				TableId tid = field.getAnnotation(TableId.class);
				if(tid != null) {
					dbField = tid.value();
				}
			}else {
				dbField=tf.value();
			}
			convertMap.put(dbField, ele.getValue());
		}
		return convertMap;
	}
}
